package com.ys.peony.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.ImageFormat;
import android.hardware.Camera;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.SparseArray;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ys.peony.R;
import com.ys.peony.app.HttpURL;
import com.ys.peony.base.BaseActivity;
import com.ys.peony.http.JCHttpManagerUtils;
import com.ys.peony.http.base.BaseRespCallBack;
import com.ys.peony.model.BusiTypeFileModel;
import com.ys.peony.ui.adapter.TakePicPreviewAdapter;
import com.ys.peony.ui.view.HorizontalListView;
import com.ys.peony.ui.widget.imagecheckdialog.ImageCheckDialog;
import com.ys.peony.ui.widget.imagecheckdialog.ImageCheckDialogModel;
import com.ys.peony.ui.widget.imagecheckdialog.PickCheckModel;
import com.ys.peony.ui.widget.imagecheckdialog.TouchImageView;
import com.ys.peony.utils.FileManager;
import com.ys.peony.utils.ImageLoadUtils;
import com.ys.peony.utils.LoadingProgressUtils;
import com.ys.peony.utils.LogUtil;
import com.ys.peony.utils.SharePreferencesUtils;
import com.ys.peony.utils.ToastUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import butterknife.BindView;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * Created by yml on 17/5/21.
 */

public class TakePicturesActivity extends BaseActivity implements View.OnClickListener {

    private String TAG = TakePicturesActivity.class.getSimpleName();

    @BindView(R.id.flashlight_btn)
    RelativeLayout flashlightBtn;

    @BindView(R.id.switch_camera_imgbtn)
    ImageButton switchCameraImgBtn;

    @BindView(R.id.camera_surfaceview)
    SurfaceView cameraSurfaceView;

    @BindView(R.id.cancel_btn)
    TextView cancelBtn;

    @BindView(R.id.finish_btn)
    TextView finishBtn;

    @BindView(R.id.take_pic_imgbtn)
    ImageButton takePicImgBtn;

    @BindView(R.id.preview_img_hlv)
    HorizontalListView previewHlv;


    private SurfaceView surfaceView;
    private SurfaceHolder surfaceHolder;
    private Camera camera;

    protected boolean isPreview = false; //摄像区域是否准备良好

    private TakePicPreviewAdapter adapter;
    private ArrayList<String> picList = new ArrayList<String>();
    private int cameraPosition = 1;
    private boolean isOpen = false;

    private BusiTypeFileModel busiTypeFileModel;
    private String fileType = "1";//1:借款人资料  2:补件资料  3:打回补件资料
    private String loanId;
    private String patchId;
    private boolean isTakingPic = false;

    private int pWidth = 720;

    @Override
    protected int getContentResId() {
        return R.layout.activity_take_picture;
    }

    protected void initWindow() {
        // 隐藏标题栏
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 隐藏状态栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    @Override
    public void initView() {
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        pWidth = wm.getDefaultDisplay().getWidth();
        initCamera();

        adapter = new TakePicPreviewAdapter(this, picList);
        previewHlv.setAdapter(adapter);

        flashlightBtn.setOnClickListener(this);
        switchCameraImgBtn.setOnClickListener(this);
        cancelBtn.setOnClickListener(this);
        finishBtn.setOnClickListener(this);
        takePicImgBtn.setOnClickListener(this);

        previewHlv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String[] pics = new String[picList.size()];
                for (int i = 0; i < picList.size(); i++) {
                    pics[i] = picList.get(i);
                }
                ImageCheckDialogModel model = new ImageCheckDialogModel();
                model.setPicType(PickCheckModel.pic_type_local);
                model.setCurrentIndex(position);
                model.setLocalPics(pics);
                final ImageCheckDialog imageCheckDialog = ImageCheckDialog.newInstance(model);
                imageCheckDialog.setCallback(new ImageCheckDialog.ImageCheckDialogCallback() {

                    @Override
                    public void onImageTaped(TouchImageView imageView, int index) {
                        imageCheckDialog.dismiss();
                    }
                });
                imageCheckDialog.show(getSupportFragmentManager(), "dddd");
            }
        });
        Bundle bd = getIntent().getExtras();
        if (bd != null) {
            busiTypeFileModel = (BusiTypeFileModel) bd.getSerializable("busiTypeFileModel");
            fileType = bd.getString("fileType");
            loanId = bd.getString("loanId");
            patchId = bd.getString("patchId");
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.flashlight_btn:
                if (isOpen) {
                    close();
                } else {
                    open();
                }
                break;
            case R.id.switch_camera_imgbtn:
                switchCamera();
                break;
            case R.id.cancel_btn:
                finish();
                break;
            case R.id.finish_btn:
                uploadFiles();
                break;
            case R.id.take_pic_imgbtn:
                if (!isTakingPic) {
                    takePhotos();
                }
                break;

        }
    }


    //初始化摄像头
    private void initCamera() {
        surfaceView = (SurfaceView) findViewById(R.id.camera_surfaceview);
        SurfaceHolder cameraSurfaceHolder = surfaceView.getHolder();
        cameraSurfaceHolder.addCallback(new SurfaceHolder.Callback() {

            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                camera = Camera.open();
                iniCameraParameters(true, holder);
                isPreview = true;
                surfaceHolder = holder;
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width,
                                       int height) {
                surfaceHolder = holder;
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                if (camera != null) {
                    if (isPreview) {
                        camera.stopPreview();
                        isPreview = false;
                    }
                    camera.release();
                    camera = null; // 记得释放Camera
                }
                surfaceView = null;
                surfaceHolder = null;
            }
        });
        //开发时建议设置
        cameraSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

    }

    private void iniCameraParameters(boolean isSetParams, SurfaceHolder holder) {
        //设置Camera的角度/方向
        camera.setDisplayOrientation(90);
        if (isSetParams) {
            Camera.Parameters parameters = camera.getParameters();
            parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);//1连续对焦
            List<Camera.Size> previews = parameters.getSupportedPictureSizes();
            boolean initPicSize = false;
            for (int i = 0; i < previews.size(); i++) {
                LogUtil.i("bbbb", "___" + previews.get(i).width + "_____" + previews.get(i).height);
                LogUtil.i("bbbb", "___pWidth:" + pWidth);
                if (previews.get(i).width == pWidth && previews.get(i).height > previews.get(i).width) {
                    initPicSize = true;
                    parameters.setPictureSize(previews.get(i).width, previews.get(i).height);
                    parameters.setPreviewSize(previews.get(i).width, previews.get(i).height);
                    break;
                } else if (previews.get(i).height == pWidth && previews.get(i).height < previews.get(i).width) {
                    parameters.setPictureSize(previews.get(i).width, previews.get(i).height);
                    parameters.setPreviewSize(previews.get(i).width, previews.get(i).height);
                    break;
                }
            }

            parameters.setPictureFormat(ImageFormat.JPEG);// 设置照片的输出格式
            parameters.set("jpeg-quality", 85);// 照片质量
            camera.setParameters(parameters);
        }
        try {
            camera.setPreviewDisplay(holder);
        } catch (IOException e) {
            e.printStackTrace();
        }
        camera.startPreview();
        camera.cancelAutoFocus();// 2如果要实现连续的自动对焦，这一句必须加上
    }

    private void takePhotos() {
        try {
            if (picList.size() >= 5) {
                ToastUtils.showToast(this, "最多只能拍5张");
                return;
            }
            if (camera != null) {
                isTakingPic = true;
                camera.takePicture(null, null, new Camera.PictureCallback() {
                    @Override
                    public void onPictureTaken(byte[] data, Camera camera) {
                        camera.startPreview();
                        new SavePictureTask().execute(data);
                        LogUtil.i(TAG, "=====拍照成功=====");
                    }
                }); // 拍照
            }
        } catch (Exception e) {
            e.printStackTrace();
            isTakingPic = false;
        }
    }

    public void removeImg(int position) {
        picList.remove(position);
        adapter.setDate(picList);
    }

    class SavePictureTask extends AsyncTask<byte[], String, String> {
        @Override
        protected String doInBackground(byte[]... params) {
            String path = FileManager.getFileDirectory();
            File out = new File(path);
            if (!out.exists()) {
                out.mkdirs();
            }

            String picPath = path + "/" + new Date().getTime() + ".jpg";
            File picture = new File(picPath);
            try {
                FileOutputStream fos = new FileOutputStream(picture.getPath());
                fos.write(params[0]);
                fos.close();

                boolean saveFlag = ImageLoadUtils.takePicToSave(picPath, TakePicturesActivity.this);

                if (saveFlag) {
                    //TODO 放入列表 刷新列表界面
                    if (picList != null && picList.size() <= 5) {
                        picList.add(picture.getAbsolutePath());
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                adapter.setDate(picList);
                            }
                        });
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                isTakingPic = false;
            }
            return null;
        }
    }

    private void switchCamera() {
        //切换前后摄像头
        int cameraCount = 0;
        Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
        cameraCount = Camera.getNumberOfCameras();//得到摄像头的个数

        for (int i = 0; i < cameraCount; i++) {
            Camera.getCameraInfo(i, cameraInfo);//得到每一个摄像头的信息
            if (cameraPosition == 1) {
                //现在是后置，变更为前置
                if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {//代表摄像头的方位，CAMERA_FACING_FRONT前置      CAMERA_FACING_BACK后置
                    camera.stopPreview();//停掉原来摄像头的预览
                    camera.release();//释放资源
                    camera = null;//取消原来摄像头
                    camera = Camera.open(i);//打开当前选中的摄像头
                    iniCameraParameters(false, surfaceHolder);
                    cameraPosition = 0;
                    break;
                }
            } else {
                //现在是前置， 变更为后置
                if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {//代表摄像头的方位，CAMERA_FACING_FRONT前置      CAMERA_FACING_BACK后置
                    camera.stopPreview();//停掉原来摄像头的预览
                    camera.release();//释放资源
                    camera = null;//取消原来摄像头
                    camera = Camera.open(i);//打开当前选中的摄像头
                    iniCameraParameters(false, surfaceHolder);
                    cameraPosition = 1;
                    break;
                }
            }

        }
    }

    /**
     * 打开闪光灯
     *
     * @return
     */
    private void open() {
        try {
            camera = Camera.open();
            camera.startPreview();
            Camera.Parameters parameters = camera.getParameters();
            parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
            camera.setParameters(parameters);
            iniCameraParameters(true, surfaceHolder);
            isOpen = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭闪光灯
     *
     * @return
     */
    private void close() {
        try {
            Camera.Parameters parameters = camera.getParameters();
            parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
            camera.setParameters(parameters);
//            camera.release();
            iniCameraParameters(true, surfaceHolder);

            isOpen = false;

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (camera != null) {
            camera.stopPreview();
            camera.release();
            camera = null;
        }
    }

    /**
     * 提交图片
     */
    private void uploadFiles() {
        if (picList == null || picList.size() <= 0) {
            finish();
            return;
        }
        LoadingProgressUtils.showProgressDialog(this);
        JCHttpManagerUtils httpManager = new JCHttpManagerUtils();
        String httpUrl = HttpURL.saveBusiLoanInfo;
        if ("2".equals(fileType)) {
            httpUrl = HttpURL.savePatchBusiLoanInfo;
        } else if ("3".equals(fileType)) {
            httpUrl = HttpURL.saveBackPatchBusiLoanInfo;
        }
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        builder.addFormDataPart("userId", SharePreferencesUtils.getInstance().getUserModel().getId())
                .addFormDataPart("loanId", loanId)
                .addFormDataPart("typeId", busiTypeFileModel.getType_id())//(必传) Long 类别主键，客户主键或抵押物主键
                .addFormDataPart("clientInfoId", busiTypeFileModel.getClient_info_id() + "")//(必传) Long 客户资料主键
                .addFormDataPart("type", busiTypeFileModel.getType())//(必传) String 类别，1-客户，2-抵押物
                .addFormDataPart("remakes", "");
        if ("3".equals(fileType)) {
            builder.addFormDataPart("patchId", patchId);
        }
        for (int j = 0; j < picList.size(); j++) {
            builder.addFormDataPart("files", new File(picList.get(j)).getName(), RequestBody.create(MediaType.parse("image/*"), new File(picList.get(j))));
        }
        httpManager.uploadPics(httpUrl, builder.build(), new BaseRespCallBack(this) {
            public void onRespSuccess(String respStr) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Intent it = new Intent();
                        setResult(RESULT_OK, it);
                        finish();
                    }
                });
            }

            @Override
            public void onRespFailure(String msg) {
                super.onRespFailure(msg);
                ToastUtils.showToast(TakePicturesActivity.this, msg);
            }
        });
    }
}
